// 扩展采购发票表单功能
frappe.ui.form.on('Purchase Invoice', {
    refresh: function(frm) {
        if (frm.doc.docstatus === 0) {
            frm.add_custom_button(
                __("Receive from Supplier"),
                function() {
                    // 校验供应商是否已填写
                    if (!frm.doc.supplier) {
                        frappe.msgprint({
                            title: __('Supplier Required'),
                            indicator: 'red',
                            message: __('Please select a supplier first.')
                        });
                        return;
                    }
                    show_wip_transfer_dialog(frm);
                },
                __("Get Items From")
            );
        }
    }
});

// 自定义对话框函数
function show_wip_transfer_dialog(frm) {
    // 创建对话框
    const d = new frappe.ui.Dialog({
        title: __("Select Receive from Supplier"),
        fields: [
            {
                fieldtype: 'Section Break',
                label: __('Filters')
            },
            {
                fieldtype: 'MultiSelectList',
                label: __('Work Orders'),
                fieldname: 'work_orders',
                get_data: function(txt) {
                    return frappe.db.get_link_options('Work Order', txt, {
                        docstatus: 1,
                        company: frm.doc.company
                    });
                },
                description: __('Select multiple work orders')
            },
            {
                fieldtype: 'Column Break'
            },
            {
                fieldtype: 'Link',
                label: __('Supplier'),
                fieldname: 'supplier',
                options: 'Supplier',
                read_only: 1,
                default: frm.doc.supplier || ''
            },
            {
                fieldtype: 'Column Break'
            },
            {
                fieldtype: 'Date Range',
                label: __('Subcontracting In Date Range'),
                fieldname: 'date_range'
            },
            {
                fieldtype: 'Section Break'
            },
            {
                fieldtype: 'Data',
                label: __('Search'),
                fieldname: 'search_term',
                description: __('Search by WIP Transfer, Supplier, Work Order, Item')
            },
            {
                fieldtype: 'Section Break'
            },
            {
                fieldtype: 'HTML',
                fieldname: 'results_area'
            }
        ],
        primary_action_label: __('Create Invoice'),
        primary_action: function() {
            const selected = d.$wrapper.find('input[type=checkbox]:checked');
            if (!selected.length) {
                frappe.msgprint(__('Please select at least one item'));
                return;
            }
            
            // 收集选中的 WIP Transfer 名称和 WIP Transfer Item 名称
            const selected_transfers = {};
            const selected_items = [];
            
            selected.each(function() {
                const transfer_name = $(this).attr('data-name');
                const item_name = $(this).attr('data-item-name');
                
                if (!transfer_name || !item_name) {
                    console.error('Missing data attributes on checkbox:', this);
                    return;
                }
                
                if (!selected_transfers[transfer_name]) {
                    selected_transfers[transfer_name] = [];
                }
                
                selected_transfers[transfer_name].push(item_name);
                selected_items.push(item_name);
            });
            
            // 检查是否有有效的选中项目
            if (selected_items.length === 0) {
                frappe.msgprint(__('All items have already been invoiced or no valid items selected'));
                return;
            }
            
            // 将选中的 WIP Transfer 名称转换为数组
            const selected_names = Object.keys(selected_transfers);
            
            // 调用后端方法
            frappe.call({
                method: "light_mes.light_mes.doctype.wip_transfer.wip_transfer.map_selected_items",
                args: {
                    source_names: selected_names,
                    selected_items: selected_items,
                    target_doc: frm.doc ? JSON.stringify(frm.doc) : null
                },
                freeze: true,
                freeze_message: __("Creating Purchase Invoice..."),
                callback: function(r) {
                    if (!r.exc) {
                        frappe.model.sync(r.message);
                        frm.refresh();
                        d.hide();
                    }
                }
            });
        }
    });
    
    // 增加对话框宽度
    d.$wrapper.find('.modal-dialog').css('max-width', '90%');
    d.$wrapper.find('.modal-dialog').css('width', '1500px');
    d.$wrapper.find('.modal-content').css('max-height', '80vh');
    
    // 显示对话框
    d.show();
    
    // 初始加载数据
    load_data();
    
    // 添加事件监听器
    d.fields_dict.search_term.input.addEventListener('keyup', function(e) {
        if (e.keyCode === 13) {
            load_data();
        }
    });
    
    d.fields_dict.supplier.df.onchange = function() {
        load_data();
    };
    
    d.fields_dict.date_range.df.onchange = function() {
        load_data();
    };
    
    d.fields_dict.work_orders.df.onchange = function() {
        load_data();
    };
    
    // 加载数据函数
    function load_data() {
        const search_term = d.get_value('search_term') || '';
        const supplier = d.get_value('supplier') || '';
        const date_range = d.get_value('date_range') || [];
        const work_orders = d.get_value('work_orders') || [];
        
        let filters = {
            docstatus: 1,
            type: "Receive from Supplier",
            company: frm.doc.company
        };
        
        if (supplier) {
            filters.from_supplier = supplier;
        }
        
        // 构建日期过滤条件
        if (date_range && date_range.length === 2) {
            filters.date_from = date_range[0];
            filters.date_to = date_range[1];
        }
        
        // 显示加载指示器
        d.fields_dict.results_area.$wrapper.html(`
            <div class="text-center" style="margin-top: 20px;">
                <div class="spinner"></div>
                <div>${__('Loading...')}</div>
            </div>
        `);
        
        frappe.call({
            method: "light_mes.light_mes.doctype.wip_transfer.wip_transfer.get_wip_transfer_for_invoice",
            args: {
                doctype: "Wip Transfer",
                txt: search_term,
                searchfield: "name",
                start: 0,
                page_len: 50,
                filters: filters,
                work_orders: work_orders,
                as_dict: 1
            },
            callback: function(r) {
                if (r.message && r.message.length) {
                    let html = `
                    <div style="margin-bottom: 10px;">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" id="select-all"> ${__('Select All')}
                            </label>
                        </div>
                    </div>
                    <div style="max-height: 400px; overflow-y: auto;">
                        <table class="table table-bordered table-hover" style="table-layout: fixed;">
                            <colgroup>
                                <col style="width: 30px;">
                                <col style="width: 140px;">
                                <col style="width: 50px;">
                                <col style="width: 140px;">
                                <col style="width: 100px;">
                                <col style="width: 120px;">
                                <col style="width: 80px;">
                                <col style="width: 80px;">
                                <col style="width: 100px;">
                                <col style="width: 100px;">
                                <col style="width: 80px;">
                                <col style="width: 90px;">
                                <col style="width: 80px;">
                                <col style="width: 80px;">
                                <col style="width: 80px;">
                                <col style="width: 80px;">
                                <col style="width: 140px;">
                                <col style="width: 100px;">
                            </colgroup>
                            <thead>
                                <tr style="height: 40px;">
                                    <th style="width: 30px; text-align: center; vertical-align: middle;"></th>
                                    <th style="text-align: left; vertical-align: middle;">${__('Wip Transfer Name')}</th>
                                    <th style="text-align: center; vertical-align: middle;">${__('Row #')}</th>
                                    <th style="text-align: left; vertical-align: middle;">${__('Work Order')}</th>
                                    <th style="text-align: left; vertical-align: middle;">${__('Production Item')}</th>
                                    <th style="text-align: left; vertical-align: middle;">${__('Item Name')}</th>
                                    <th style="text-align: center; vertical-align: middle;">${__('Operation')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Quality Qty')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Invoiced Qty')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Pending Invoice Qty')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Scrap Qty')}</th>
                                    <th style="text-align: center; vertical-align: middle;">${__('Status')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Rate')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Tax Rate')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Tax Amount')}</th>
                                    <th style="text-align: right; vertical-align: middle;">${__('Amount')}</th>
                                    <th style="text-align: left; vertical-align: middle;">${__('Supplier')}</th>
                                    <th style="text-align: center; vertical-align: middle;">${__('In Date')}</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                    
                    // 过滤工单
                    let filtered_items = r.message;
                    if (work_orders && work_orders.length) {
                        filtered_items = r.message.filter(item => 
                            work_orders.includes(item.work_order)
                        );
                    }
                    
                    filtered_items.forEach(function(item) {
                        html += `
                            <tr>
                                <td style="text-align: center;"><input type="checkbox" data-name="${item.wip_transfer_name}" data-item-name="${item.wip_transfer_item_name}"></td>
                                <td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.wip_transfer_name}</td>
                                <td style="text-align: center;">${item.item_idx || ''}</td>
                                <td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.work_order || ''}</td>
                                <td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.production_item || ''}</td>
                                <td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.item_name || ''}</td>
                                <td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">${item.operation || ''}</td>
                                <td style="text-align: right;">${item.qty || 0}</td>
                                <td style="text-align: right;">${item.invoiced_qty || 0}</td>
                                <td style="text-align: right;">${item.pending_qty || 0}</td>
                                <td style="text-align: right;">${item.scrap_qty || 0}</td>
                                <td style="text-align: center;">${__(item.status) || __('Not Invoiced')}</td>
                                <td style="text-align: right;">${format_currency(item.rate || 0)}</td>
                                <td style="text-align: right;">${format_number(item.tax_rate * 100 || 0, null, 2)}%</td>
                                <td style="text-align: right;">${format_currency(item.tax_amount || 0)}</td>
                                <td style="text-align: right;">${format_currency(item.amount || 0)}</td>
                                <td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.from_supplier || ''}</td>
                                <td style="text-align: center;">${frappe.datetime.str_to_user(item.date) || ''}</td>
                            </tr>
                        `;
                    });
                    
                    html += `
                            </tbody>
                        </table>
                    </div>
                    `;
                    
                    d.fields_dict.results_area.$wrapper.html(html);
                    
                    // 添加全选功能
                    d.$wrapper.find('#select-all').on('click', function() {
                        const checked = $(this).prop('checked');
                        
                        // 只选中有效的复选框（有data-name和data-item-name属性的）
                        d.$wrapper.find('tbody input[type=checkbox]').each(function() {
                            if ($(this).attr('data-name') && $(this).attr('data-item-name')) {
                                $(this).prop('checked', checked);
                            }
                        });
                    });
                    
                    // 添加行点击选择功能
                    d.$wrapper.find('tbody tr').on('click', function(e) {
                        if (e.target.type !== 'checkbox') {
                            const checkbox = $(this).find('input[type=checkbox]');
                            checkbox.prop('checked', !checkbox.prop('checked'));
                        }
                    });
                    
                    // 添加鼠标悬停显示完整内容的功能
                    d.$wrapper.find('td[style*="overflow: hidden"]').each(function() {
                        $(this).attr('title', $(this).text());
                    });
                } else {
                    d.fields_dict.results_area.$wrapper.html(`
                        <div class="text-center text-muted" style="margin-top: 20px;">
                            ${__('No matching Receive from Supplier entries found')}
                        </div>
                    `);
                }
            }
        });
    }
} 